//
//  UserInfoModel.swift
//  MyLottery
//
//  Created by wujunjie on 2018/7/31.
//  Copyright © 2018年 wujunjie. All rights reserved.
//
let UserInfoKey = "MyLotteryUserInfoKey"
import UIKit
class UserInfoModel : NSObject{
     ///单例
    static let userAccount : UserInfoModel = UserInfoModel()
    ///用户 id
    var uid : String?
    ///用户昵称
    var screen_name: String?
    ///头像
    var avatar_large : String?
    ///授权令牌
    var access_token : String?
//    ///过期秒数
    var expires_in :TimeInterval = 0 {
        didSet {
            expired_date = NSDate(timeInterval: expires_in, since: NSDate() as Date)
        }
    }
    ///过期日期
    var expired_date : NSDate?
     ///是否过期
    var isExpired : Bool {
        return   expired_date?.compare(NSDate() as Date) == .orderedAscending
    }
    ///是否登录
    var isLogin : Bool {
        return access_token != nil && isExpired != true
    }
    override var description: String {
        return dictionaryWithValues(forKeys: ["uid", "screen_name", "avatar_large", "access_token", "expired_date"]).description
    }
    
    //构造函数
    override init() {
        super.init()
        //从本地读取的数据来初始化对象
        readUserAccount()
    }
    
   /// kvc的异常处理
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
}

///MARK:-用户信息相关
extension UserInfoModel{
    public   func saveUserAccount(dict: [String:AnyObject]){   ///存储用户信息
        setValuesForKeys(dict)
        var userAccountDict = [String:AnyObject]()
        if   let avatar_large_ = dict["avatar_large"] as? String{
            userAccountDict["avatar_large"] = avatar_large_ as AnyObject
        }

        if let screen_name = dict["screen_name"] as? String{
            userAccountDict["screen_name"] = screen_name as AnyObject
        }

        if let uid_ = dict["uid"] as? String{
            userAccountDict["uid"] = uid_ as AnyObject
        }

        if  let expires_in_ = dict["expires_in"] as? TimeInterval {
            userAccountDict["expires_in"] = expires_in_ as AnyObject
        }
        
         if  let access_token_ = dict["access_token"] as? String{
            userAccountDict["access_token"] = access_token_ as AnyObject
        }
        //3. 把字典存起来
        UserDefaults.standard.set(userAccountDict, forKey: UserInfoKey)
    }

    public func readUserAccount(){
        ///读取用户信息
        if let userDict = UserDefaults.standard.object(forKey: UserInfoKey) as? [String: AnyObject] {
            //2. 使用 userDict 给单例的属性赋值
            setValuesForKeys(userDict)
        }
    }
}

